<template>
  <div class="app-container">
    <el-row :gutter="20" class="main-content">
      <el-col :xs="24" :sm="24" :md="16" :lg="16" :xl="16">
        <div class="table-container">
          <h2 class="section-title">订单列表</h2>
          <div class="table-wrapper">
            <div class="table-content">
              <el-table 
                :data="tableData" 
                stripe 
                style="width: 100%"
                :header-cell-style="{
                  background: '#f5f7fa',
                  color: '#606266',
                  fontWeight: 'bold',
                  textAlign: 'center'
                }"
                :cell-style="{
                  padding: '12px 0',
                  textAlign: 'center'
                }"
              >
                <el-table-column prop="bookingNumber" label="订单" width="140" />
                <el-table-column prop="name" label="乘车人" width="100" />
                <el-table-column prop="date" label="乘车日期" width="110" />
        <el-table-column prop="from" label="出发地" />
        <el-table-column prop="to" label="目的地" />
                <el-table-column prop="bookingStatus" label="订单状态">
          <template #default="scope">
                    <el-tag :type="scope.row.bookingStatus === 'CONFIRMED' ? 'success' : 'danger'">
                      {{ scope.row.bookingStatus === "CONFIRMED" ? "已确认" : "已取消" }}
                    </el-tag>
          </template>
        </el-table-column>
                <el-table-column prop="carType.typeName" label="车辆类型" />
                <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
                    <el-button size="small" type="primary" class="action-button" @click="handleEdit(scope.row)">
              修改订单
            </el-button>
                    <el-button size="small" type="danger" class="action-button" @click="handleCancel(scope.row)">
              取消订单
            </el-button>
          </template>
        </el-table-column>
      </el-table>
            </div>
          </div>
          <div class="pagination-wrapper">
            <el-pagination
              v-model="currentPage"
              :page-size="pageSize"
              :total="total"
              :page-sizes="[5, 10, 20, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              @current-change="handlePageChange"
              @size-change="handleSizeChange"
            />
          </div>
        </div>
    </el-col>

      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" class="chat-column">
        <div class="chat-container">
          <h2 class="section-title">智能助手</h2>
          <div class="timeline-container" ref="timelineContainer">
            <el-timeline>
          <el-timeline-item
              v-for="(activity, index) in activities"
              :key="index"
              :icon="activity.icon"
              :type="activity.type"
              :color="activity.color"
              :size="activity.size"
              :hollow="activity.hollow"
              :timestamp="activity.timestamp"
                class="timeline-item"
          >
                <div class="message-content">{{ activity.content }}</div>
          </el-timeline-item>
        </el-timeline>
      </div>
          <div class="button-container">
            <el-button 
              type="danger" 
              size="small" 
              class="action-btn"
              @click="handleQuickAction('cancel')"
            >
              取消订单
            </el-button>
            <el-button 
              type="success" 
              size="small" 
              class="action-btn"
              @click="handleQuickAction('book')"
            >
              预约订单
            </el-button>
            <el-button 
              type="warning" 
              size="small" 
              class="action-btn"
              @click="handleQuickAction('modify')"
            >
              修改订单
            </el-button>
            <el-button 
              type="primary" 
              size="small" 
              class="action-btn"
              @click="handleQuickAction('query')"
            >
              查询订单
            </el-button>
          </div>
          <div class="input-container">
          <el-input
              v-model="msg"
              type="text"
              placeholder="请输入您的问题..."
              class="chat-input"
              @keydown.enter="sendMsg()"
            >
              <template #append>
                <el-button @click="sendMsg()" type="primary">发送</el-button>
              </template>
            </el-input>
          </div>
      </div>
    </el-col>
  </el-row>

    <!-- 修改订单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
    >
      <el-form :model="formData" label-width="100px">
        <el-form-item label="订单号">
          <el-input v-model="formData.bookingNumber" disabled />
        </el-form-item>
        <el-form-item label="乘车人">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="乘车日期">
          <el-date-picker
            v-model="formData.date"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="出发地">
          <el-input v-model="formData.from" />
        </el-form-item>
        <el-form-item label="目的地">
          <el-input v-model="formData.to" />
        </el-form-item>
        <el-form-item label="车辆类型">
          <el-select v-model="formData.carTypeId" placeholder="请选择车辆类型">
            <el-option
              v-for="type in carTypes"
              :key="type.id"
              :label="type.typeName"
              :value="type.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, watch } from "vue";
import axios from 'axios'//引入axios
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, ChatDotRound } from '@element-plus/icons-vue'
import { MoreFilled } from '@element-plus/icons-vue'

interface Message {
  content: string
  timestamp: string
  color: string
  icon?: any
  type?: string
  size?: string
  hollow?: boolean
}

interface CarType {
  id: number
  typeName: string
}

interface Booking {
  bookingNumber: string
  name: string
  date: string
  from: string
  to: string
  carTypeId: number
  carType: CarType
  bookingStatus: string
}

const activities = ref<Message[]>([
  {
    content: '⭐欢迎使用速达出行服务！请问有什么可以帮您的?',
        timestamp: new Date().toLocaleDateString() + " " + new Date().toLocaleTimeString(),
        color: '#0bbd87',
      },
    ]);
    const msg = ref('');
const tableData = ref<Booking[]>([]);
const timelineContainer = ref<HTMLElement | null>(null);
    let count = 2;
    let eventSource;
const dialogVisible = ref(false)
const dialogTitle = ref('')
const currentBooking = ref<Booking | null>(null)
const formData = ref({
  bookingNumber: '',
  name: '',
  date: '',
  from: '',
  to: '',
  carTypeId: null as number | null
})
const carTypes = ref<CarType[]>([])
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);

const scrollToBottom = async () => {
  await nextTick();
  if (timelineContainer.value) {
    timelineContainer.value.scrollTop = timelineContainer.value.scrollHeight;
  }
};

watch(activities, () => {
  scrollToBottom();
}, { deep: true });

    const sendMsg = () => {
      if (eventSource) {
        eventSource.close();
      }

      activities.value.push(
          {
            content: `你:${msg.value}`,
            timestamp: new Date().toLocaleDateString() + " " + new Date().toLocaleTimeString(),
            size: 'large',
            type: 'primary',
            icon: MoreFilled,
      color: '#409eff',
          },
      );

      activities.value.push(
          {
            content: 'waiting...',
            timestamp: new Date().toLocaleDateString() + " " + new Date().toLocaleTimeString(),
            color: '#0bbd87',
          },
      );

      // sse: 服务端推送 Server-Sent Events
      eventSource = new EventSource(`http://localhost:8080/ai/stream?message=${msg.value}`);
      msg.value='';
      eventSource.onmessage = (event) => {
        if (event.data === '[complete]') {
          count = count + 2;
          eventSource.close();
          getBookings();  // 每次对话完后刷新列表
          return;
        }
        activities.value[count].content += event.data;
      };
      eventSource.onopen = (event) => {
        activities.value[count].content = '';
      };
    };

const getBookings = async (page = currentPage.value, size = pageSize.value) => {
  try {
    const response = await axios.get(`http://localhost:8080/api/bookings?page=${page-1}&size=${size}`)
    tableData.value = response.data.content
    total.value = response.data.totalElements
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  }
}

const getCarTypes = async () => {
  try {
    const response = await axios.get('http://localhost:8080/api/car-types')
    carTypes.value = response.data
  } catch (error) {
    console.error('获取车辆类型失败:', error)
    ElMessage.error('获取车辆类型失败')
  }
}

const handlePageChange = (page: number) => {
  currentPage.value = page;
  getBookings(page);
}

// 监听每页条数变化（如果后续支持）
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
  getBookings(1, size);
}

    // Use onMounted to call getBookings when the component is mounted
    onMounted(() => {
      getBookings();
  getCarTypes();
});

// 修改订单
const handleEdit = (row) => {
  dialogTitle.value = '修改订单'
  currentBooking.value = row
  formData.value = {
    bookingNumber: row.bookingNumber,
    name: row.name,
    date: row.date,
    from: row.from,
    to: row.to,
    carTypeId: row.carType?.id ?? null
  }
  dialogVisible.value = true
}

// 取消订单
const handleCancel = async (row) => {
  try {
    const confirmResult = await ElMessageBox.confirm(
      '确定要取消该订单吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    if (confirmResult === 'confirm') {
      const response = await axios.post(`http://localhost:8080/api/bookings/${row.bookingNumber}/cancel`)
      if (response.status === 200) {
        ElMessage.success('订单已取消')
        getBookings() // 刷新列表
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      const errorMessage = error.response?.data || '取消订单失败'
      ElMessage.error(errorMessage)
    }
  }
}

// 提交修改
const handleSubmit = async () => {
  try {
    if (!currentBooking.value) return;
    const response = await axios.put(`http://localhost:8080/api/bookings/${currentBooking.value.bookingNumber}`, formData.value)
    if (response.status === 200) {
      ElMessage.success('订单修改成功')
      dialogVisible.value = false
      getBookings() // 刷新列表
    }
  } catch (error) {
    console.error('修改订单失败:', error)
    const errorMessage = error.response?.data || '修改订单失败'
    ElMessage.error(errorMessage)
  }
}

// 快速操作按钮处理
const handleQuickAction = (action: string) => {
  let message = '';
  switch (action) {
    case 'cancel':
      message = '我要取消订单';
      break;
    case 'book':
      message = '我要预约订单';
      break;
    case 'modify':
      message = '我要修改订单';
      break;
    case 'query':
      message = '我要查询订单';
      break;
  }
  
  // 将消息设置到输入框并自动发送
  msg.value = message;
  sendMsg();
}
</script>

<style scoped>
.app-container {
  padding: 20px;
  height: 100vh;
  background-color: #f0f2f5;
  box-sizing: border-box;
  overflow: hidden;
}

.main-content {
  max-width: 1400px;
  margin: 0 auto;
  height: calc(100vh - 40px);
  display: flex;
}

.section-title {
  margin-bottom: 20px;
  color: #1a1a1a;
  font-size: 1.5rem;
  font-weight: 600;
  letter-spacing: 0.5px;
}

.table-container {
  background: linear-gradient(145deg, #ffffff, #f8f9fa);
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  border: 1px solid rgba(0, 0, 0, 0.05);
}

/* 表格区域容器 */
.table-wrapper {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* 表格内容区域 */
.table-content {
  flex: 1;
  overflow: auto;
  /* 自定义滚动条样式 */
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 #f1f1f1;
}

/* Webkit浏览器滚动条样式 */
.table-content::-webkit-scrollbar {
  width: 8px;
}

.table-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.table-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.table-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 表格样式 */
.table-content :deep(.el-table) {
  height: 500px;
}

.table-content :deep(.el-table__body-wrapper) {
  overflow-y: auto;
  max-height: 100%;
}

.table-content :deep(.el-table__header-wrapper) {
  position: sticky;
  top: 0;
  z-index: 1;
}

/* 分页区域 */
.pagination-wrapper {
  flex-shrink: 0;
  padding-top: 10px;
  border-top: 1px solid rgba(0, 0, 0, 0.05);
  text-align: right;
}

.chat-column {
  height: 100%;
}

.chat-container {
  background: linear-gradient(145deg, #ffffff, #f8f9fa);
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  height: 100%;
  display: flex;
  flex-direction: column;
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.timeline-container {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  margin-bottom: 20px;
}

.timeline-item {
  padding: 8px 0;
}

.message-content {
  background: #f8f9fa;
  padding: 12px 16px;
  border-radius: 8px;
  margin: 5px 0;
  line-height: 1.6;
  color: #2c3e50;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
  border: 1px solid rgba(0, 0, 0, 0.03);
}

.input-container {
  padding: 10px 0;
}

.chat-input {
  width: 100%;
}

.chat-input :deep(.el-input__wrapper) {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border-radius: 8px;
  background: #ffffff;
}

.chat-input :deep(.el-input__inner) {
  color: #2c3e50;
}

.action-button {
  margin: 0 5px;
}

:deep(.el-table) {
  --el-table-border-color: rgba(0, 0, 0, 0.05);
  --el-table-header-bg-color: #f8f9fa;
  --el-table-row-hover-bg-color: #f8f9fa;
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f8f9fa !important;
  color: #1a1a1a !important;
  font-weight: 600;
}

:deep(.el-table td) {
  color: #2c3e50;
}

:deep(.el-button--primary) {
  background: linear-gradient(145deg, #409eff, #3a8ee6);
  border: none;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

:deep(.el-button--danger) {
  background: linear-gradient(145deg, #f56c6c, #e64242);
  border: none;
  box-shadow: 0 2px 8px rgba(245, 108, 108, 0.2);
}

:deep(.el-tag--success) {
  background: linear-gradient(145deg, #67c23a, #5daf34);
  border: none;
  color: white;
  box-shadow: 0 2px 8px rgba(103, 194, 58, 0.2);
}

:deep(.el-tag--danger) {
  background: linear-gradient(145deg, #f56c6c, #e64242);
  border: none;
  color: white;
  box-shadow: 0 2px 8px rgba(245, 108, 108, 0.2);
}

@media (max-width: 768px) {
  .app-container {
    padding: 10px;
    height: auto;
    overflow: auto;
  }
  
  .main-content {
    height: auto;
    flex-direction: column;
  }
  
  .table-container,
  .chat-container {
    margin-bottom: 20px;
    height: auto;
  }
  
  .chat-container {
    height: 500px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.button-container {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  gap: 8px;
}

.action-btn {
  flex: 1;
  font-size: 12px;
  padding: 8px 12px;
  }
</style>
